package com.jeeplus.modules.monitor.task;

import com.jeeplus.common.utils.DbUtils;
import com.jeeplus.common.utils.MobileUtils;
import com.jeeplus.common.utils.concurrent.jsr166e.ConcurrentHashMapV8;
import com.jeeplus.modules.monitor.entity.Result;
import com.jeeplus.modules.monitor.entity.ScheduleJob;
import com.jeeplus.modules.monitor.entity.Task;
import com.jeeplus.modules.tools.utils.MultiDBUtils;
import net.sf.json.JSON;
import net.sf.json.JSONObject;
import org.quartz.DisallowConcurrentExecution;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @author Administrator
 * @title: TaskSql
 * @projectName jeeplus
 * @description: TODO
 * @date 2019/8/713:10
 */
@DisallowConcurrentExecution
public class TaskSql extends Task {
    /*日志*/
    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void run(ScheduleJob scheduleJob) {
        try {
            JSONObject jsonObject = JSONObject.fromObject(scheduleJob.getParameter());
            String scriptInfo = jsonObject.getString("Script");
            String serviceName = jsonObject.getString("ServiceName");
            Long startTime = System.currentTimeMillis();
            ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(10);//创建只有2个线程的线程池
            List<Future<String>> resultList = new ArrayList<>();
            for (String p : serviceName.split(",")) {
                if (!p.isEmpty()) {
                    TaskScript calculator = new TaskScript(scriptInfo, p);
                    Future<String> result = executor.submit(calculator);
                    resultList.add(result);
                }
            }
            for (int i = 0; i < resultList.size(); i++) {
                logger.info(String.format("第 %d 个线程 执行结果是: %s\n", i + 1, resultList.get(i).get()));
            }
            executor.shutdown();
            Long endTime = System.currentTimeMillis();
            logger.info(String.format("使用时间 = [" + (endTime - startTime) + "]"));
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }
    }

    private class TaskScript implements Callable<String> {
        private String sql;
        private String serviceName;

        private TaskScript(String sql, String serviceName) {
            this.sql = sql;
            this.serviceName = serviceName;
        }

        public String call() throws Exception {
            String error = "脚本执行失败";
            try {
                List<String> sqlList = new ArrayList<>();
                for (String s : sql.split(";")) {
                    if (!s.trim().isEmpty()) {
                        sqlList.add(s);
                    }
                }
                MultiDBUtils.get(serviceName).getJdbcTemplate().batchUpdate(sqlList.toArray(new String[sqlList.size()]));
                error="脚本执行成功!";
            } catch (Exception e) {
                error=e.getMessage();
                logger.error(error);
            }
            return error;
        }
    }
}
